<template>
  <el-upload
    class="avatar-uploader"
    :action="url"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :headers="myHeaders"
    :data="{
      method,
    }"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    <div slot="tip" class="el-upload__tip">
      {{ tips }}
    </div>
  </el-upload>
</template>

<script>
  import store from "@/store";
  import { baseURL } from "@/config/settings";
  export default {
    name: "AppUpload",
    model: {
      prop: "imageUrl",
      event: "updateImgUrl",
    },
    props: {
      imageUrl: {
        type: String,
        default: "",
      },
      tips: {
        type: String,
        default: "只能上传jpg,png文件，且不超过2M",
      },
      method: {
        type: String,
        default: "profile",
      },
    },
    data() {
      return {
        url: baseURL + "upload",
        myHeaders: {
          token: store.getters["user/accessToken"],
        },
      };
    },
    mounted() {},
    methods: {
      handleAvatarSuccess(res, file) {
        let img = URL.createObjectURL(file.raw);
        this.$emit("updateImgUrl", img);
        this.$emit("result", res.data);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpeg";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
    },
  };
</script>
<style lang="scss" scoped>
  .avatar-uploader {
    ::v-deep {
      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        &:hover {
          border-color: #409eff;
        }
      }
    }
  }
  .el-upload__tip {
    width: 240px;
    text-align: center;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 240px;
    height: 158px;
    line-height: 158px;
    text-align: center;
  }
  .avatar {
    width: 240px;
    height: 158px;
    display: block;
  }
</style>
